<template>
    <div class="attachUploader">
        <van-cell-group inset>
                <van-cell title="附件" icon="link-o" size="large" :border="false">
                    <template #value>
                        <van-uploader
                            :after-read="afterRead"   
                            accept=".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.pdf,.jpg,.jpeg,.png"                         
                            :max-count="1"
                        >
                        <van-button type="primary"   size="small" icon="plus">添加</van-button>
                        </van-uploader>
                        
                    </template>
                </van-cell>
                <div v-for="item in list">
                  <van-cell :border="false" size="large" class="attachUploadItem" v-if="(!item.onFtp && !item.id) || (item.onFtp && item.id)">
                  <template #title>
                    <span class="custom-title" style="color:blue">{{ item.orgFileName }}</span>                    
                  </template>
                  <template #value>
                    <van-icon name="delete-o" class="search-icon" size="26px" color="red" @click="handleDelete(item)"/>
                  </template>
                </van-cell>
                </div>
                
            </van-cell-group>
    </div>
</template>
<script lang="ts" setup> 
import {fileService} from '@/api/request';
import DialogTool from '@/util/DialogTool';
import type { UploaderFileListItem } from 'vant';
import type { Attach } from '@/types/workflow';
import { ref, watch } from 'vue';
import { showConfirmDialog } from 'vant';


interface AttachUploaderProps{
  modelValue?:Attach[]
}

const props = defineProps<AttachUploaderProps>();
const emit = defineEmits(['update:modelValue']);

const list = ref<Attach[]>([]);

watch(()=>props.modelValue,()=>{
  if(props.modelValue){
    console.log('update attach list')
    list.value = props.modelValue;
  }
})

const afterRead =(file:UploaderFileListItem|UploaderFileListItem[])=>{
      
      // 例如，上传文件到服务器
      //@ts-ignore
      if(file.file){        
        //@ts-ignore
        uploadFile(file.file);
      }
}
    
const uploadFile = (file:File)=>{
      const formData = new FormData();
      formData.append('file', file);
      DialogTool.showLoading("正在上传");
 
      // 使用 axios 发送文件到服务器
      fileService.post('/attach/uploadFile',formData,
        {
            headers: {
            'Content-Type': 'multipart/form-data'
            }
        }
      ).then((resp)=>{
        var {filePath,origFileName,attachSize} = resp.data.params;
        list.value.push({
            fileName:filePath,
            orgFileName:origFileName,
            attaSize:attachSize,
            onFtp:false
        });
        DialogTool.closeToast();
        DialogTool.showToast("上传成功");

        emit('update:modelValue',list.value);

      }).catch(error => {
        DialogTool.closeToast();
        console.error('上传失败', error);
        DialogTool.showAlert("上传失败！");
      });;

}

const handleDelete = (item:Attach)=>{
  
  showConfirmDialog({  
  message:
    '确定要删除附件吗',
  })
  .then(() => {
    doDelete(item)
  })
  .catch(() => {
    // on cancel
  });
}

const doDelete =(item:Attach)=>{
  if(!item.onFtp){//本地文件，直接删除
    var temp:Attach[] = [];
    list.value.forEach((ele)=>{
      if(ele.fileName != item.fileName){
        temp.push(ele);
      }
    })
    list.value = temp;
  }

  if(item.onFtp){//已上传服务器，并且保存
    list.value.forEach((ele)=>{
      if(ele.fileName == item.fileName){
          ele.onFtp=false;   
      }
    })    
  }

  emit("update:modelValue",list.value)
}

</script>
<style lang="less" scoped>
</style>
<style>
.attachUploader .attachUploadItem .van-cell__value{
   flex: initial;
    width: 50px;
}

.attachUploader .van-cell__title{
  white-space: pre-wrap;
}
</style>
